package com.yl.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yl.model.Users;
import com.yl.service.IUsersService;
import com.yl.util.JWTUtil;
import com.yl.util.ResponseData;
@ResponseBody
@Controller
@RequestMapping("/users")
public class UsersController {

	
	@Resource
	private IUsersService usersService;
	//前台用户登录
	@RequestMapping("/loginusers.do")
	public ResponseData login(Users users) {
		Users u = usersService.login(users);
		ResponseData responseData = ResponseData.ok();
		if(null!=u) {//数据库验证通过
			//生成token
    		String token = JWTUtil.generToken("1", "Jersey-Security-Basic", users.getPhone());
    		//向浏览器返回token，客户端受到此token后存入cookie中，或者h5的本地存储中
    		responseData.putDataValue("token", token);
    		//以及用户
    		responseData.putDataValue("user", u);
		}else {
			//用户或者密码错误
    		responseData=ResponseData.customerError();
		}
		return responseData;
	}

	
	//注册
	@RequestMapping("/register.do")
	public int register(Users users){
		return usersService.register(users);
	}
	//修改密码
	@RequestMapping("/editPwd.do")
	public String editPwd(String oldPwd,String newPwd,HttpSession session) {
		Users user = (Users) session.getAttribute("user");
		//只有用户登录，才能修改密码
		if(user!=null) {
			int n =  usersService.editPwd(oldPwd, newPwd,user);			
			if(n>0) {
				//将会话中的用户密码改成新密码
				user.setUser_password(newPwd);
				session.setAttribute("user", user);
				return "success";
			}else {
				return "fail";
			}
		}return "fail";			
	}
	//修改个人信息
	@RequestMapping("/editusers.do")
	public int edit(Users users){
		return usersService.edit(users);
	}
	
	//显示个人信息
		@RequestMapping("/findByIdusers.do")
		public Users findById(int user_id){
			return usersService.findById(user_id);
		}
		//查询所有用户
		@ResponseBody
		@RequestMapping("/findAllusers.do")
		public Map<String,Object> findAll(){
			return usersService.findAll();
		}
	
}
